package FeedMaker;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;

public class FeedDownloader extends Thread
{
	private FeedReader reader_;
	public int download_check_interval = 1000 * 60 * 20; // 20 minute
	public String save_path_;
	
	private TorrentFeeder torrent_feeder_;
	
	FeedDownloader( FeedReader reader ) {
		reader_ = reader;
		save_path_ = "ddanji_radio_feeds/";
		torrent_feeder_ = new TorrentFeeder();
	}
	
	public void run()
	{
		Hashtable<String,String> feeds = new Hashtable<String,String>();
		List< DdanjiEntry > entrys = new ArrayList< DdanjiEntry >();
		
		try {
			while( !Thread.currentThread().isInterrupted() )
			{
				entrys.clear();
				
				reader_.feeds_.get_elements(feeds);
				
				for( Enumeration<String> f = feeds.keys(); f.hasMoreElements(); )
				{
					String feed = f.nextElement();
					
					String feed_title = feeds.get(feed);
					
					if( feed_title.length() > 0 )
					{
						entrys.clear();
						
						reader_.entrys_.get_elements( feed_title, entrys );
						
						for( DdanjiEntry entry : entrys )
						{
							boolean changed = false;
							
							if( entry.download( feed_title, save_path_ ) )
							{
								changed = true;
							}
							
							if( entry.upload(feed_title, save_path_) )
							{
								changed = true;
								torrent_feeder_.update( entrys, feed_title, save_path_ );
							}
							
							if( changed )
							{
								reader_.entrys_.save();
							}
						}
					}
				}
				
				
				Thread.sleep( download_check_interval );
			}
		}
		catch( InterruptedException ex ) {
			entrys = null;
		}
		
		entrys = null;
	}
}